<?php defined('SYSPATH') or die('No direct access allowed.');

class Controller_CPanel_Pages extends Controller_CPanel {

    public function action_index() {

        //Check forms

        if (isset($_POST['save_page'])) {
            self::save_page();
        } elseif (isset($_POST['remove_page'])) {
            self::remove_page();
        }

        //Render content

        $this->title = __('Pages');
        $view = View::factory('cpanel/content/page');

        $settings = Kohana::$config->load('app');

        $page = Arr::get($_POST, 'page');
        if ($page == null)
            $page = Arr::get($_GET, 'page', 'index');

        $new = false;

        if ($page == 'new') {
            $page = __('New page');
            $new = true;
        }

        $pages = array('index');

        $orm_pages = ORM::factory('page')->find_all();
        foreach ($orm_pages as $orm_page) {
            if (!in_array($orm_page->page, $pages)) {
                $pages[] = $orm_page->page;
            }
        }

        $view->new = $new;
        $view->page = $page;
        $view->pages = $pages;
        $view->languages = Arr::get($settings, 'languages', array());

        $this->content = $view->render();
    }

    private function save_page() {

        $_page = Arr::get($_POST, 'page');
        $template = Arr::get($_POST, 'template');

        $languages = Arr::get(Kohana::$config->load('app'), 'languages', array());

        foreach ($languages as $lang => $desc) {
            $page = ORM::factory('page')
                    ->where('lang', '=', $lang)
                    ->where('page', '=', $_page)
                    ->find();

            if (!$page->loaded()) {
                $page = ORM::factory('page');
                $page->lang = $lang;
                $page->page = $_page;
            }

            $page->template = $template;
            $page->title = Arr::get($_POST, 'title_' . $lang, '');
            $page->content = Arr::get($_POST, 'content_' . $lang, '');

            try {
                $page->save();
            } catch (ORM_Validation_Exception $e) {
                $errors = $e->errors('validation');
                foreach ($errors as $error)
                    parent::add_message($error, 'error');
                return;
            }
        }

        parent::add_message('Saved!!!', 'success');
    }

    private function remove_page() {
        $page = Arr::get($_POST, 'page');

        if ($page == 'index') {
            parent::add_message('Can\'t remove index page!!!', 'error');
            return;
        }
        
        DB::delete()
                ->table('pages')
                ->where('page', '=', $page)
                ->execute();
        
        $_POST['page'] = 'index';
        parent::add_message('Removed!!!', 'success');
    }

}